home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-installer.exe / bin / gi / _option.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2014-12-31  |  12KB  |  343 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. '''GOption command line parser
  5.  
  6. Extends optparse to use the GOptionGroup, GOptionEntry and GOptionContext
  7. objects. So it is possible to use the gtk, gnome_program and gstreamer command
  8. line groups and contexts.
  9.  
  10. Use this interface instead of the raw wrappers of GOptionContext and
  11. GOptionGroup in glib.
  12. '''
  13. import sys
  14. import optparse
  15. from optparse import OptParseError, OptionError, OptionValueError, BadOptionError, OptionConflictError
  16. from module import get_introspection_module
  17. if sys.version_info >= (3, 0):
  18.     _basestring = str
  19.     
  20.     _bytes = lambda s: s.encode()
  21. else:
  22.     _basestring = basestring
  23.     _bytes = str
  24. from gi._gi import _glib
  25. from gi._error import GError
  26. GLib = get_introspection_module('GLib')
  27. OPTION_CONTEXT_ERROR_QUARK = GLib.quark_to_string(GLib.option_error_quark())
  28. __all__ = [
  29.     'OptParseError',
  30.     'OptionError',
  31.     'OptionValueError',
  32.     'BadOptionError',
  33.     'OptionConflictError',
  34.     'Option',
  35.     'OptionGroup',
  36.     'OptionParser',
  37.     'make_option']
  38.  
  39. class Option(optparse.Option):
  40.     """Represents a command line option
  41.  
  42.     To use the extended possibilities of the GOption API Option
  43.     (and make_option) are extended with new types and attributes.
  44.  
  45.     Types:
  46.         filename   The supplied arguments are read as filename, GOption
  47.                    parses this type in with the GLib filename encoding.
  48.  
  49.     :ivar optional_arg:
  50.         This does not need a arguement, but it can be supplied.
  51.     :ivar hidden:
  52.         The help list does not show this option
  53.     :ivar in_main:
  54.         This option apears in the main group, this should only
  55.         be used for backwards compatibility.
  56.  
  57.     Use Option.REMAINING as option name to get all positional arguments.
  58.  
  59.     .. NOTE::
  60.         Every argument to an option is passed as utf-8 coded string, the only
  61.         exception are options which use the 'filename' type, its arguments
  62.         are passed as strings in the GLib filename encoding.
  63.  
  64.     For further help, see optparse.Option.
  65.     """
  66.     TYPES = optparse.Option.TYPES + ('filename',)
  67.     ATTRS = optparse.Option.ATTRS + [
  68.         'hidden',
  69.         'in_main',
  70.         'optional_arg']
  71.     REMAINING = '--' + GLib.OPTION_REMAINING
  72.     
  73.     def __init__(self, *args, **kwargs):
  74.         optparse.Option.__init__(self, *args, **kwargs)
  75.         if not self._long_opts:
  76.             raise ValueError('%s at least one long option name.')
  77.         if len(self._long_opts) < len(self._short_opts):
  78.             raise ValueError('%s at least more long option names than short option names.')
  79.         if not self.help:
  80.             raise ValueError('%s needs a help message.', self._long_opts[0])
  81.  
  82.     
  83.     def _set_opt_string(self, opts):
  84.         if self.REMAINING in opts:
  85.             self._long_opts.append(self.REMAINING)
  86.         optparse.Option._set_opt_string(self, opts)
  87.         if len(self._short_opts) > len(self._long_opts):
  88.             raise OptionError('goption.Option needs more long option names than short option names')
  89.  
  90.     
  91.     def _to_goptionentries(self):
  92.         flags = 0
  93.         if self.hidden:
  94.             flags |= GLib.OptionFlags.HIDDEN
  95.         if self.in_main:
  96.             flags |= GLib.OptionFlags.IN_MAIN
  97.         if self.takes_value() or self.optional_arg:
  98.             flags |= GLib.OptionFlags.OPTIONAL_ARG
  99.         
  100.         flags |= GLib.OptionFlags.NO_ARG
  101.         if self.type == 'filename':
  102.             flags |= GLib.OptionFlags.FILENAME
  103.         for long_name, short_name in zip(self._long_opts, self._short_opts):
  104.             yield (long_name[2:], _bytes(short_name[1]), flags, self.help, self.metavar)
  105.         
  106.         for long_name in self._long_opts[len(self._short_opts):]:
  107.             yield (long_name[2:], _bytes('\x00'), flags, self.help, self.metavar)
  108.         
  109.  
  110.  
  111.  
  112. class OptionGroup(optparse.OptionGroup):
  113.     '''A group of command line options.
  114.  
  115.     :param str name:
  116.         The groups name, used to create the --help-{name} option
  117.     :param str description:
  118.         Shown as title of the groups help view
  119.     :param str help_description:
  120.         Shown as help to the --help-{name} option
  121.     :param list option_list:
  122.         The options used in this group, must be option.Option()
  123.     :param dict defaults:
  124.         A dicitionary of default values
  125.     :param translation_domain:
  126.            Sets the translation domain for gettext().
  127.  
  128.     .. NOTE::
  129.         This OptionGroup does not exactly map the optparse.OptionGroup
  130.         interface. There is no parser object to supply, but it is possible
  131.         to set default values and option_lists. Also the default values and
  132.         values are not shared with the OptionParser.
  133.  
  134.     To pass a OptionGroup into a function which expects a GOptionGroup (e.g.
  135.     gnome_program_init() ). OptionGroup.get_option_group() can be used.
  136.  
  137.     For further help, see optparse.OptionGroup.
  138.     '''
  139.     
  140.     def __init__(self, name, description, help_description = '', option_list = None, defaults = None, translation_domain = None):
  141.         optparse.OptionContainer.__init__(self, Option, 'error', description)
  142.         self.name = name
  143.         self.parser = None
  144.         self.help_description = help_description
  145.         if defaults:
  146.             self.defaults = defaults
  147.         self.values = None
  148.         self.translation_domain = translation_domain
  149.         if option_list:
  150.             for option in option_list:
  151.                 self.add_option(option)
  152.             
  153.  
  154.     
  155.     def _create_option_list(self):
  156.         self.option_list = []
  157.         self._create_option_mappings()
  158.  
  159.     
  160.     def _to_goptiongroup(self, parser):
  161.         
  162.         def callback(option_name, option_value, group):
  163.             if option_name.startswith('--'):
  164.                 opt = self._long_opt[option_name]
  165.             else:
  166.                 opt = self._short_opt[option_name]
  167.             
  168.             try:
  169.                 opt.process(option_name, option_value, self.values, parser)
  170.             except OptionValueError:
  171.                 error = sys.exc_info()[1]
  172.                 gerror = GError(str(error))
  173.                 gerror.domain = OPTION_CONTEXT_ERROR_QUARK
  174.                 gerror.code = GLib.OptionError.BAD_VALUE
  175.                 gerror.message = str(error)
  176.                 raise gerror
  177.  
  178.  
  179.         group = _glib.OptionGroup(self.name, self.description, self.help_description, callback)
  180.         if self.translation_domain:
  181.             group.set_translation_domain(self.translation_domain)
  182.         entries = []
  183.         for option in self.option_list:
  184.             entries.extend(option._to_goptionentries())
  185.         
  186.         group.add_entries(entries)
  187.         return group
  188.  
  189.     
  190.     def get_option_group(self, parser = None):
  191.         ''' Returns the corresponding GOptionGroup object.
  192.  
  193.         Can be used as parameter for gnome_program_init(), gtk_init().
  194.         '''
  195.         self.set_values_to_defaults()
  196.         return self._to_goptiongroup(parser)
  197.  
  198.     
  199.     def set_values_to_defaults(self):
  200.         for option in self.option_list:
  201.             default = self.defaults.get(option.dest)
  202.             if isinstance(default, _basestring):
  203.                 opt_str = option.get_opt_string()
  204.                 self.defaults[option.dest] = option.check_value(opt_str, default)
  205.                 continue
  206.         self.values = optparse.Values(self.defaults)
  207.  
  208.  
  209.  
  210. class OptionParser(optparse.OptionParser):
  211.     '''Command line parser with GOption support.
  212.  
  213.     :param bool help_enabled:
  214.         The --help, --help-all and --help-{group} options are enabled (default).
  215.     :param bool ignore_unknown_options:
  216.         Do not throw a exception when a option is not knwon, the option
  217.         will be in the result list.
  218.  
  219.     .. NOTE::
  220.         The OptionParser interface is not the exactly the same as the
  221.         optparse.OptionParser interface. Especially the usage parameter
  222.         is only used to show the metavar of the arguements.
  223.  
  224.     OptionParser.add_option_group() does not only accept OptionGroup instances
  225.     but also glib.OptionGroup, which is returned by gtk_get_option_group().
  226.  
  227.     Only glib.option.OptionGroup and glib.option.Option instances should
  228.     be passed as groups and options.
  229.  
  230.     For further help, see optparse.OptionParser.
  231.     '''
  232.     
  233.     def __init__(self, *args, **kwargs):
  234.         if 'option_class' not in kwargs:
  235.             kwargs['option_class'] = Option
  236.         self.help_enabled = kwargs.pop('help_enabled', True)
  237.         self.ignore_unknown_options = kwargs.pop('ignore_unknown_options', False)
  238.         optparse.OptionParser.__init__(self, add_help_option = False, *args, **kwargs)
  239.  
  240.     
  241.     def set_usage(self, usage):
  242.         if usage is None:
  243.             self.usage = ''
  244.         elif usage.startswith('%prog'):
  245.             self.usage = usage[len('%prog'):]
  246.         else:
  247.             self.usage = usage
  248.  
  249.     
  250.     def _to_goptioncontext(self, values):
  251.         if self.description:
  252.             parameter_string = self.usage + ' - ' + self.description
  253.         else:
  254.             parameter_string = self.usage
  255.         context = _glib.OptionContext(parameter_string)
  256.         context.set_help_enabled(self.help_enabled)
  257.         context.set_ignore_unknown_options(self.ignore_unknown_options)
  258.         for option_group in self.option_groups:
  259.             if isinstance(option_group, _glib.OptionGroup):
  260.                 g_group = option_group
  261.             else:
  262.                 g_group = option_group.get_option_group(self)
  263.             context.add_group(g_group)
  264.         
  265.         
  266.         def callback(option_name, option_value, group):
  267.             if option_name.startswith('--'):
  268.                 opt = self._long_opt[option_name]
  269.             else:
  270.                 opt = self._short_opt[option_name]
  271.             opt.process(option_name, option_value, values, self)
  272.  
  273.         main_group = _glib.OptionGroup(None, None, None, callback)
  274.         main_entries = []
  275.         for option in self.option_list:
  276.             main_entries.extend(option._to_goptionentries())
  277.         
  278.         main_group.add_entries(main_entries)
  279.         context.set_main_group(main_group)
  280.         return context
  281.  
  282.     
  283.     def add_option_group(self, *args, **kwargs):
  284.         if isinstance(args[0], _basestring):
  285.             optparse.OptionParser.add_option_group(self, OptionGroup(self, *args, **kwargs))
  286.             return None
  287.         if None(args) == 1 and not kwargs:
  288.             if isinstance(args[0], OptionGroup):
  289.                 if not args[0].parser:
  290.                     args[0].parser = self
  291.                 if args[0].parser is not self:
  292.                     raise ValueError('invalid OptionGroup (wrong parser)')
  293.             if isinstance(args[0], _glib.OptionGroup):
  294.                 self.option_groups.append(args[0])
  295.                 return None
  296.         optparse.OptionParser.add_option_group(self, *args, **kwargs)
  297.  
  298.     
  299.     def _get_all_options(self):
  300.         options = self.option_list[:]
  301.         for group in self.option_groups:
  302.             if isinstance(group, optparse.OptionGroup):
  303.                 options.extend(group.option_list)
  304.                 continue
  305.         return options
  306.  
  307.     
  308.     def _process_args(self, largs, rargs, values):
  309.         context = self._to_goptioncontext(values)
  310.         rargs[:] = context.parse([
  311.             sys.argv[0]] + rargs)[1:]
  312.  
  313.     
  314.     def parse_args(self, args = None, values = None):
  315.         if not args:
  316.             pass
  317.         old_args = []
  318.         
  319.         try:
  320.             (options, args) = optparse.OptionParser.parse_args(self, args, values)
  321.         except GError:
  322.             error = sys.exc_info()[1]
  323.             if error.domain != OPTION_CONTEXT_ERROR_QUARK:
  324.                 raise 
  325.             if error.code == GLib.OptionError.BAD_VALUE:
  326.                 raise OptionValueError(error.message)
  327.             if error.code == GLib.OptionError.UNKNOWN_OPTION:
  328.                 raise BadOptionError(error.message)
  329.             if error.code == GLib.OptionError.FAILED:
  330.                 raise OptParseError(error.message)
  331.             raise 
  332.  
  333.         for group in self.option_groups:
  334.             for key, value in group.values.__dict__.items():
  335.                 options.ensure_value(key, value)
  336.             
  337.         
  338.         args = args[2:-len(old_args)]
  339.         return (options, args)
  340.  
  341.  
  342. make_option = Option
  343.